package com.ybbase.framework.service.flow.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ybbase.framework.mapper.flow.InstanceRecordMapper;
import com.ybbase.framework.mapper.flow.NodeConfigMapper;
import com.ybbase.framework.mapper.flow.NodeRecordMapper;
import com.ybbase.framework.mapper.system.OrganizationMapper;
import com.ybbase.framework.mapper.system.UserMapper;
import com.ybbase.framework.model.enumeration.FlowApproveOpinion;
import com.ybbase.framework.model.po.flow.InstanceRecord;
import com.ybbase.framework.model.po.flow.NodeConfig;
import com.ybbase.framework.model.po.flow.NodeRecord;
import com.ybbase.framework.model.po.system.Organization;
import com.ybbase.framework.model.po.system.User;
import com.ybbase.framework.model.vo.BusinessEntityVO;
import com.ybbase.framework.service.flow.ProcessCoreService;
import java.util.*;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;
import org.activiti.engine.impl.pvm.process.TransitionImpl;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author cg
 * @date 2019-08-26 14:19
 * @DEC 操作流程核心类，暂时不支持会签操作
 */
@Service
public class ProcessCoreServiceImpl implements ProcessCoreService {

    @Autowired
    protected RepositoryService repositoryService;

    @Autowired
    protected RuntimeService runtimeService;

    @Autowired
    protected TaskService taskService;

    @Autowired
    protected FormService formService;

    @Autowired
    protected HistoryService historyService;

    @Autowired
    protected ProcessEngine processEngine;

    @Autowired
    protected InstanceRecordMapper instanceRecordMapper;

    @Autowired
    protected UserMapper userMapper;

    @Autowired
    protected OrganizationMapper organizationMapper;

    @Autowired
    protected NodeRecordMapper nodeRecordMapper;

    @Autowired
    protected NodeConfigMapper nodeConfigMapper;


    /**
     * 根据当前任务ID、退回节点ID、variables流程存储参数进行退回流程
     * @author cg
     * @date 2019-09-02 19:45
     * @param taskId 当前任务ID
     * @param activityId 退回节点ID
     * @param variables 流程存储参数
     * @param businessEntityVO 业务类
     * @throws Exception
     */
    @Override
    public void backProcess(String taskId, String activityId, Map<String, Object> variables, BusinessEntityVO businessEntityVO) throws Exception {
        if (StringUtils.isEmpty(activityId)) {
            throw new Exception("退回目标节点ID为空！");
        }
        // 查找所有并行任务节点，同时退回
        List<Task> taskList = findTaskListByKey(findProcessInstanceByTaskId(
                taskId).getId(), findTaskById(taskId).getTaskDefinitionKey());
        for (Task task : taskList) {
            commitProcess(task.getId(), variables, activityId,businessEntityVO);
        }
    }

    /**
     * 根据当前任务ID、取回节点ID进行取回流程，撤回
     * @param
     * @return
     * @author cg
     * @date 2020-03-07 17:45
     * @since cloud2.0
    */
    @Override
    public void executeCallBackProcess(String taskId,Map<String, Object> variables,String userID, String activityId, BusinessEntityVO businessEntityVO) {
        try {
            if (StringUtils.isEmpty(activityId)) {
                throw new Exception("目标节点ID为空！");
            }
            // 取得当前任务
            HistoricTaskInstance currTask = historyService
                    .createHistoricTaskInstanceQuery().taskId(taskId)
                    .singleResult();
//          //根据流程id查询代办任务中流程信息
//            List<Task> taskList = taskService.createTaskQuery().processInstanceId(currTask.getProcessInstanceId()).list();
//            //取回流程接点 当前任务id 取回任务id
//            if (taskList!=null&&!taskList.isEmpty()){
//                for(Task task:taskList){
//                    historyService.deleteHistoricTaskInstance(task.getId());
//                    commitProcess(task.getId(), variables, activityId,businessEntityVO);
//                }
//            }
//            //删除历史流程走向记录
//            historyService.deleteHistoricTaskInstance(currTask.getId());
            this.revoke(currTask.getProcessInstanceId(),userID,variables);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void revoke(String objId,String userId,Map<String, Object> variables) throws Exception {
        List<Task> taskList = taskService.createTaskQuery().processInstanceId(objId).list();
        if(taskList==null) {
            throw new ServiceException("流程未启动或已执行完成，无法撤回");
        }
        for(Task task:taskList){
            List<HistoricTaskInstance> htiList = historyService.createHistoricTaskInstanceQuery()
                    //.processInstanceBusinessKey(objId)
                    .processInstanceId(objId)
                    .taskId(task.getId())
                    .orderByTaskCreateTime()
                    .asc()
                    .list();
            String myTaskId = null;
            HistoricTaskInstance myTask = null;
            for(HistoricTaskInstance hti : htiList) {
                if(userId.equals(hti.getAssignee())) {
                    myTaskId = hti.getId();
                    myTask = hti;
                    break;
                }
            }
            if(null==myTaskId) {
                throw new ServiceException("该任务非当前用户提交，无法撤回");
            }
            String processDefinitionId = myTask.getProcessDefinitionId();
            ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
            //变量
            String myActivityId = null;
            List<HistoricActivityInstance> haiList = historyService.createHistoricActivityInstanceQuery()
                    .executionId(myTask.getExecutionId()).finished().list();
            for(HistoricActivityInstance hai : haiList) {
                if(myTaskId.equals(hai.getTaskId())) {
                    myActivityId = hai.getActivityId();
                    break;
                }
            }
            FlowNode myFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(myActivityId);
            Execution execution = runtimeService.createExecutionQuery().executionId(task.getExecutionId()).singleResult();
            String activityId = execution.getActivityId();
            FlowNode flowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(activityId);
            //记录原活动方向
            List<SequenceFlow> oriSequenceFlows = new ArrayList<SequenceFlow>();
            oriSequenceFlows.addAll(flowNode.getOutgoingFlows());
            //清理活动方向
            flowNode.getOutgoingFlows().clear();
            //建立新方向
            List<SequenceFlow> newSequenceFlowList = new ArrayList<SequenceFlow>();
            SequenceFlow newSequenceFlow = new SequenceFlow();
            newSequenceFlow.setId("newSequenceFlowId");
            newSequenceFlow.setSourceRef(flowNode.getId());
            newSequenceFlow.setTargetRef(myFlowNode.getId());
            newSequenceFlowList.add(newSequenceFlow);
            flowNode.setOutgoingFlows(newSequenceFlowList);
            taskService.addComment(task.getId(), task.getProcessInstanceId(), "撤回");
            //完成任务
            taskService.complete(task.getId(),variables);
            //恢复原方向
            flowNode.setOutgoingFlows(oriSequenceFlows);
        }

    }

    /**
     * 提交流程/流程转向
     * @author cg
     * @date 2019-09-02 19:51
     * @param taskId 当前任务ID
     * @param variables 流程变量
     * @param activityId 流程转向执行任务节点ID，此参数为空，默认为提交操作
     * @param businessEntityVO 业务类
     * @throws Exception
     */
    @Override
    public void commitProcess(String taskId, Map<String, Object> variables, String activityId, BusinessEntityVO businessEntityVO) throws Exception {
        if (variables == null) {
            variables = new HashMap<String, Object>();
        }
        // 跳转节点为空，默认提交操作
        if (StringUtils.isEmpty(activityId)) {
            taskService.complete(taskId, variables);
        } else {
            // 流程转向操作
            turnTransition(taskId, activityId, variables);
        }
        InstanceRecord in = getInstanceRecordByVO(businessEntityVO);
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(in.getRunProcessInstanceId()).singleResult();
        HistoricTaskInstance historicTaskInstance = processEngine.getHistoryService().createHistoricTaskInstanceQuery().
                processInstanceId(in.getRunProcessInstanceId()).taskId(taskId).singleResult();
        List<HistoricTaskInstance>  hisTaskList = historyService.createHistoricTaskInstanceQuery()
                .taskId(taskId).processInstanceId(in.getRunProcessInstanceId()).orderByTaskCreateTime().asc().list();
        Task task = new TaskEntity();
        if(processInstance == null){
            this.updateProcessInstance(historicTaskInstance,businessEntityVO);
        }
        if(hisTaskList!=null&&!hisTaskList.isEmpty()){
            ((TaskEntity) task).setId(hisTaskList.get(0).getId());
            ((TaskEntity) task).setTaskDefinitionKey(hisTaskList.get(0).getTaskDefinitionKey());
            this.saveActivitiRecord(task,in,historicTaskInstance, businessEntityVO, variables);
        }

    }
    /**
     * 获取业务实例记录信息
     * @param businessEntityVO 业务Vo
     * @return
     * @author cg
     * @date 2019-09-27 17:25
     * @since 4.0
     */
    @Override
    public InstanceRecord getInstanceRecordByVO(BusinessEntityVO businessEntityVO){
        QueryWrapper<InstanceRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(InstanceRecord::getBusinessId, businessEntityVO.getBusinessId());
        queryWrapper.lambda().eq(InstanceRecord::getBusinessCode, businessEntityVO.getFlowCode());
        return instanceRecordMapper.selectOne(queryWrapper);
    }

    /**
     * 更新流程实例记录
     * @author cg
     * @date 2019-09-04 10:04
     * @param historicTaskInstance 历史任务实例
     * @param businessEntityVO 业务实例
     */
    public Integer updateProcessInstance(HistoricTaskInstance historicTaskInstance,BusinessEntityVO businessEntityVO){
        QueryWrapper<InstanceRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(InstanceRecord::getIsFinish, 0);
        if (StringUtils.isNotEmpty(historicTaskInstance.getProcessInstanceId())){
            queryWrapper.lambda().eq(InstanceRecord::getRunProcessInstanceId, historicTaskInstance.getProcessInstanceId());
        }
        if (StringUtils.isNotEmpty(businessEntityVO.getBusinessId())){
            queryWrapper.lambda().eq(InstanceRecord::getBusinessId,businessEntityVO.getBusinessId());
        }
        if (StringUtils.isNotEmpty(businessEntityVO.getFlowCode())){
            queryWrapper.lambda().eq(InstanceRecord::getBusinessCode,businessEntityVO.getFlowCode());
        }
        InstanceRecord instanceRecord = instanceRecordMapper.selectOne(queryWrapper);
        if(instanceRecord!=null){
            instanceRecord.setIsFinish(1);
            instanceRecord.setEndTime(new Date());
            instanceRecordMapper.updateById(instanceRecord);
            return instanceRecord.getId();
        }
        return 0;
    }

    /**
     * 存储流程节点信息
     * @author cg
     * @date 2019-09-04 09:10
     * @param task 任务实体
     * @param ir instanceRecord实例
     * @param historicTaskInstance 历史流程实例
     * @param businessEntityVO 业务实例
     * @param variables 审核时填写的参数
     * @return 是否保存成功，成功回写存储信息的ID
     */
    public Integer saveActivitiRecord(Task task,InstanceRecord ir,HistoricTaskInstance historicTaskInstance,
                                      BusinessEntityVO businessEntityVO,Map<String, Object> variables){
        NodeRecord nodeRecord = new NodeRecord();
        if (ir!=null){
            nodeRecord.setInstanceRecordId(ir.getId());
            nodeRecord.setModelId(ir.getModelId());
            nodeRecord.setRunDefinitionId(ir.getRunDefinitionId());
            nodeRecord.setRunProcessInstanceId(ir.getRunProcessInstanceId());
            nodeRecord.setStartTime(new Date());
            nodeRecord.setTaskId(task.getId());
            nodeRecord.setNodeId(task.getTaskDefinitionKey());
            nodeRecord.setNodeName(historicTaskInstance.getName());
            nodeRecord.setBusinessId(businessEntityVO.getBusinessId());
            nodeRecord.setBusinessName(businessEntityVO.getBusinessName());
            nodeRecord.setStartTime(historicTaskInstance.getStartTime());
            nodeRecord.setEndTime(historicTaskInstance.getEndTime());
            nodeRecord.setLimitTime(historicTaskInstance.getDurationInMillis()!=null?historicTaskInstance.getDurationInMillis():0);
            nodeRecord.setAssigneeId(Integer.parseInt(StringUtils.isNotEmpty(historicTaskInstance.getAssignee())?historicTaskInstance.getAssignee():"0"));
            User user =userMapper.selectById(Integer.parseInt(StringUtils.isNotEmpty(historicTaskInstance.getAssignee())?historicTaskInstance.getAssignee():"0"));
            if(user!=null){
                nodeRecord.setAssigneeName(user.getName());
                List<Organization> list = organizationMapper.getOrgListByUserId(user.getId());
                nodeRecord.setOrganId(list.size()>0?list.get(0).getId():0);
                nodeRecord.setOrganName(list.size()>0?list.get(0).getName():"");
            }else{
                List<Organization> organizationList = organizationMapper.getOrgListByUserId(StringUtils.isNotEmpty(historicTaskInstance.getAssignee())?
                        Integer.parseInt(historicTaskInstance.getAssignee()):0);
                if(organizationList!=null&&organizationList.size()>0){
                    nodeRecord.setOrganId(organizationList.get(0).getId());
                    nodeRecord.setOrganName(organizationList.get(0).getName());
                }
            }
            List<String> list = instanceRecordMapper.getRunTaskList(ir.getRunProcessInstanceId());
            if(list!=null&&!list.isEmpty()){
                nodeRecord.setNextNodeId(list.get(0));
            }
            nodeRecord.setAssigneeContent(StringUtils.isNotEmpty(String.valueOf(variables.get(FlowApproveOpinion.APPROVE_MESSAGE.getValue())))?
                    String.valueOf(variables.get(FlowApproveOpinion.APPROVE_MESSAGE.getValue())):"");
            QueryWrapper<NodeConfig> queryNodeConfigWrapper = new QueryWrapper<>();
            queryNodeConfigWrapper.lambda().eq(NodeConfig::getFlowCode, businessEntityVO.getFlowCode());
            queryNodeConfigWrapper.lambda().eq(NodeConfig::getNodeCode, task.getTaskDefinitionKey());
            NodeConfig cc= nodeConfigMapper.selectOne(queryNodeConfigWrapper);
            nodeRecord.setApprovalResult(cc!=null&&StringUtils.isNotEmpty(cc.getFlowCode())?cc.getFlowCode() + ":" +variables.get(cc.getOrderCode()):"");
            nodeRecordMapper.insert(nodeRecord);
            return nodeRecord.getId();
        }
        return 0;
    }

    /**
     * 中止流程(特权人直接审批通过等)
     * @author cg
     * @date 2019-09-02 19:51
     * @param taskId 流程任务编码
     * @param businessEntityVO 业务类
     * @param variables 流程变量
     * @throws Exception
     */
    @Override
    public void endProcess(String taskId,Map<String, Object> variables, BusinessEntityVO businessEntityVO) throws Exception {
        ActivityImpl endActivity = findActivitiImpl(taskId, "end");
        commitProcess(taskId, variables, endActivity.getId(),businessEntityVO);
    }

    /**
     * 根据流入任务集合，查询最近一次的流入任务节点
     * @author cg
     * @date 2019-09-02 19:52
     * @param processInstance 流程实例
     * @param tempList 流入任务集合
     * @return ActivityImpl 节点实现类
     */
    @Override
    public ActivityImpl filterNewestActivity(ProcessInstance processInstance, List<ActivityImpl> tempList) {
        while (tempList.size() > 0) {
            ActivityImpl activity_1 = tempList.get(0);
            HistoricActivityInstance activityInstance_1 = findHistoricUserTask(
                    processInstance, activity_1.getId());
            if (activityInstance_1 == null) {
                tempList.remove(activity_1);
                continue;
            }

            if (tempList.size() > 1) {
                ActivityImpl activity_2 = tempList.get(1);
                HistoricActivityInstance activityInstance_2 = findHistoricUserTask(
                        processInstance, activity_2.getId());
                if (activityInstance_2 == null) {
                    tempList.remove(activity_2);
                    continue;
                }

                if (activityInstance_1.getEndTime().before(
                        activityInstance_2.getEndTime())) {
                    tempList.remove(activity_1);
                } else {
                    tempList.remove(activity_2);
                }
            } else {
                break;
            }
        }
        if (tempList.size() > 0) {
            return tempList.get(0);
        }
        return null;
    }

    /**
     * 根据任务ID和节点ID获取活动节点
     * @author cg
     * @date 2019-09-02 20:06
     * @param taskId 任务ID
     * @param activityId 活动节点ID，如果为null或""，则默认查询当前活动节点，如果为"end"，则查询结束节点
     * @return ActivityImpl 节点实现类
     * @throws Exception
     */
    @Override
    public ActivityImpl findActivitiImpl(String taskId, String activityId) throws Exception {
        // 取得流程定义
        ProcessDefinitionEntity processDefinition = findProcessDefinitionEntityByTaskId(taskId);
        // 获取当前活动节点ID
        if (StringUtils.isEmpty(activityId)) {
            activityId = findTaskById(taskId).getTaskDefinitionKey();
        }
        // 根据流程定义，获取该流程实例的结束节点
        if ("END".equals(activityId.toUpperCase())) {
            for (ActivityImpl activityImpl : processDefinition.getActivities()) {
                List<PvmTransition> pvmTransitionList = activityImpl
                        .getOutgoingTransitions();
                if (pvmTransitionList.isEmpty()) {
                    return activityImpl;
                }
            }
        }
        // 根据节点ID，获取对应的活动节点
        ActivityImpl activityImpl = ((ProcessDefinitionImpl) processDefinition).findActivity(activityId);
        if(activityImpl==null){
            activityId = findTaskById(taskId).getTaskDefinitionKey();
            activityImpl = ((ProcessDefinitionImpl) processDefinition).findActivity(activityId);
        }
        return activityImpl;
    }

    /**
     * 根据当前任务ID，查询可以退回的任务节点
     * @author cg
     * @date 2019-09-02 20:08
     * @param taskId 当前任务ID
     * @return List<ActivityImpl> 节点实现类集合
     * @throws Exception
     */
    @Override
    public List<ActivityImpl> findBackAvtivity(String taskId) throws Exception {
        List<ActivityImpl> rtnList =  iteratorBackActivity(taskId, findActivitiImpl(taskId,null),
                new ArrayList<ActivityImpl>(),new ArrayList<ActivityImpl>());
        return reverList(rtnList);
    }

    /**
     * 根据任务ID获取流程定义
     * @author cg
     * @date 2019-09-02 20:11
     * @param taskId 任务ID
     * @return ProcessDefinitionEntity 流程定义实体类
     * @throws Exception
     */
    @Override
    public ProcessDefinitionEntity findProcessDefinitionEntityByTaskId(String taskId) throws Exception {
        // 取得流程定义
        ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
                .getDeployedProcessDefinition(findTaskById(taskId).getProcessDefinitionId());

        if (processDefinition == null) {
            throw new Exception("流程定义未找到!");
        }

        return processDefinition;
    }

    /**
     * 根据任务ID获取对应的流程实例
     * @author cg
     * @date 2019-09-02 20:12
     * @param taskId 任务ID
     * @return ProcessInstance 流程实例实体
     * @throws Exception
     */
    @Override
    public ProcessInstance findProcessInstanceByTaskId(String taskId)
            throws Exception {
        // 找到流程实例
        ProcessInstance processInstance = runtimeService
                .createProcessInstanceQuery().processInstanceId(findTaskById(taskId).getProcessInstanceId())
                .singleResult();
        if (processInstance == null) {
            throw new Exception("流程实例未找到!");
        }
        return processInstance;
    }

    /**
     * 根据任务ID获得任务实例
     * @author cg
     * @date 2019-09-02 20:13
     * @param taskId 任务ID
     * @return TaskEntity 任务实体
     * @throws Exception
     */
    @Override
    public TaskEntity findTaskById(String taskId) throws Exception {
        TaskEntity task = (TaskEntity) taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task != null){
            HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
            if (historicTaskInstance!=null){
                task = new TaskEntity();
                task.setId(historicTaskInstance.getId());
                task.setName(historicTaskInstance.getName());
                task.setProcessDefinitionId(historicTaskInstance.getProcessDefinitionId());
                task.setTaskDefinitionKey(historicTaskInstance.getTaskDefinitionKey());
            }else {
                task.setId(taskId);
                task.setName(task.getName());
                task.setProcessDefinitionId(task.getProcessDefinitionId());
                task.setTaskDefinitionKey(task.getTaskDefinitionKey());
            }
        }
        if (task == null) {
            throw new Exception("任务实例未找到!");
        }
        return task;
    }

    /**
     * 根据流程实例ID和任务key值查询所有同级任务集合
     * @author cg
     * @date 2019-09-02 20:14
     * @param processInstanceId 流程实例ID
     * @param key 任务定义的KEY
     * @return List<Task> 实例列表
     */
    @Override
    public List<Task> findTaskListByKey(String processInstanceId, String key) {
        return taskService.createTaskQuery().processInstanceId(processInstanceId).taskDefinitionKey(key).active().list();
    }

    /**
     * 转办流程
     * @author cg
     * @date 2019-09-02 20:22
     * @param taskId 当前任务节点ID
     * @param userCode 被转办人Code
     */
    @Override
    public void transferAssignee(String taskId, String userCode) {
        taskService.setAssignee(taskId, userCode);
    }

    /**
     * 迭代循环流程树结构，查询当前节点可退回的任务节点
     * @author cg
     * @date 2019-09-02 20:17
     * @param taskId 当前任务ID
     * @param currActivity 当前活动节点
     * @param rtnList 存储回退节点集合
     * @param tempList 临时存储节点集合（存储一次迭代过程中的同级userTask节点）
     * @return List<ActivityImpl> 回退节点集合
     * @throws Exception
     */
    private List<ActivityImpl> iteratorBackActivity(String taskId,ActivityImpl currActivity, List<ActivityImpl> rtnList,List<ActivityImpl> tempList) throws Exception {
        // 查询流程定义，生成流程树结构
        ProcessInstance processInstance = findProcessInstanceByTaskId(taskId);
        // 当前节点的流入来源
        List<PvmTransition> incomingTransitions = currActivity.getIncomingTransitions();
        // 条件分支节点集合，userTask节点遍历完毕，迭代遍历此集合，查询条件分支对应的userTask节点
        List<ActivityImpl> exclusiveGateways = new ArrayList<ActivityImpl>();
        // 并行节点集合，userTask节点遍历完毕，迭代遍历此集合，查询并行节点对应的userTask节点
        List<ActivityImpl> parallelGateways = new ArrayList<ActivityImpl>();
        // 遍历当前节点所有流入路径
        for (PvmTransition pvmTransition : incomingTransitions) {
            TransitionImpl transitionImpl = (TransitionImpl) pvmTransition;
            ActivityImpl activityImpl = transitionImpl.getSource();
            String type = (String) activityImpl.getProperty("type");
            /**
             * 并行节点配置要求：<br>
             * 必须成对出现，且要求分别配置节点ID为:XXX_start(开始)，XXX_end(结束)
             */
            if ("parallelGateway".equals(type)) {
                // 并行路线
                String gatewayId = activityImpl.getId();
                String gatewayType = gatewayId.substring(gatewayId.lastIndexOf("_") + 1);
                if ("START".equals(gatewayType.toUpperCase())) {
                    // 并行起点，停止递归
                    return rtnList;
                } else {
                    // 并行终点，临时存储此节点，本次循环结束，迭代集合，查询对应的userTask节点
                    parallelGateways.add(activityImpl);
                }
            } else if ("startEvent".equals(type)) {
                // 开始节点，停止递归
                return rtnList;
            } else if ("userTask".equals(type)) {
                // 用户任务
                tempList.add(activityImpl);
            } else if ("exclusiveGateway".equals(type)) {
                // 分支路线，临时存储此节点，本次循环结束，迭代集合，查询对应的userTask节点
                currActivity = transitionImpl.getSource();
                exclusiveGateways.add(currActivity);
            }
        }
        /**
         * 迭代条件分支集合，查询对应的userTask节点
         */
        for (ActivityImpl activityImpl : exclusiveGateways) {
            iteratorBackActivity(taskId, activityImpl, rtnList, tempList);
        }
        /**
         * 迭代并行集合，查询对应的userTask节点
         */
        for (ActivityImpl activityImpl : parallelGateways) {
            iteratorBackActivity(taskId, activityImpl, rtnList, tempList);
        }
        /**
         * 根据同级userTask集合，过滤最近发生的节点
         */
        currActivity = filterNewestActivity(processInstance, tempList);
        if (currActivity != null) {
            // 查询当前节点的流向是否为并行终点，并获取并行起点ID
            String id = findParallelGatewayId(currActivity);
            // 并行起点ID为空，此节点流向不是并行终点，符合退回条件，存储此节点
            if (StringUtils.isEmpty(id)) {
                rtnList.add(currActivity);
            } else {// 根据并行起点ID查询当前节点，然后迭代查询其对应的userTask任务节点
                currActivity = findActivitiImpl(taskId, id);
            }
            // 清空本次迭代临时集合
            tempList.clear();
            // 执行下次迭代
            iteratorBackActivity(taskId, currActivity, rtnList, tempList);
        }
        return rtnList;
    }

    /**
     * 流程转向操作
     * @author cg
     * @date 2019-09-02 20:22
     * @param taskId 当前任务ID
     * @param activityId 目标节点任务ID
     * @param variables 流程变量
     * @throws Exception
     */
    private void turnTransition(String taskId, String activityId, Map<String, Object> variables) throws Exception {
        // 当前节点
        ActivityImpl currActivity = findActivitiImpl(taskId, null);
        // 清空当前流向
        List<PvmTransition> oriPvmTransitionList = clearTransition(currActivity);
        // 创建新流向
        TransitionImpl newTransition = currActivity.createOutgoingTransition();
        // 目标节点
        ActivityImpl pointActivity = findActivitiImpl(taskId, activityId);
        // 设置新流向的目标节点
        newTransition.setDestination(pointActivity);
        // 执行转向任务
        taskService.complete(taskId, variables);
        // 删除目标节点新流入
        pointActivity.getIncomingTransitions().remove(newTransition);
        // 还原以前流向
        restoreTransition(currActivity, oriPvmTransitionList);
    }

    /**
     * 查询指定任务节点的最新记录
     * @author cg
     * @date 2019-09-02 20:09
     * @param processInstance 流程实例
     * @param activityId 流程节点ID
     * @return HistoricActivityInstance 历史流程节点实例
     */
    private HistoricActivityInstance findHistoricUserTask(ProcessInstance processInstance, String activityId) {
        HistoricActivityInstance rtnVal = null;
        // 查询当前流程实例审批结束的历史节点
        List<HistoricActivityInstance> historicActivityInstances = historyService
                .createHistoricActivityInstanceQuery().activityType("userTask")
                .processInstanceId(processInstance.getId()).activityId(
                        activityId).finished()
                .orderByHistoricActivityInstanceEndTime().desc().list();
        if (historicActivityInstances.size() > 0) {
            rtnVal = historicActivityInstances.get(0);
        }
        return rtnVal;
    }

    /**
     * 根据当前节点，查询输出流向是否为并行终点，如果为并行终点，则拼装对应的并行起点ID
     * @author cg
     * @date 2019-09-02 20:10
     * @param activityImpl 当前节点
     * @return String 拼装的并行起点ID
     */
    private String findParallelGatewayId(ActivityImpl activityImpl) {
        List<PvmTransition> incomingTransitions = activityImpl
                .getOutgoingTransitions();
        for (PvmTransition pvmTransition : incomingTransitions) {
            TransitionImpl transitionImpl = (TransitionImpl) pvmTransition;
            activityImpl = transitionImpl.getDestination();
            String type = (String) activityImpl.getProperty("type");
            if ("parallelGateway".equals(type)) {
                // 并行路线
                String gatewayId = activityImpl.getId();
                String gatewayType = gatewayId.substring(gatewayId
                        .lastIndexOf("_") + 1);
                if ("END".equals(gatewayType.toUpperCase())) {
                    return gatewayId.substring(0, gatewayId.lastIndexOf("_"))
                            + "_start";
                }
            }
        }
        return null;
    }

    /**
     * 反向排序list集合，便于退回节点按顺序显示
     * @author cg
     * @date 2019-09-02 20:21
     * @param list
     * @return List<ActivityImpl>
     */
    private List<ActivityImpl> reverList(List<ActivityImpl> list) {
        List<ActivityImpl> rtnList = new ArrayList<ActivityImpl>();
        // 由于迭代出现重复数据，排除重复
        for (int i = list.size(); i > 0; i--) {
            if (!rtnList.contains(list.get(i - 1))){
                rtnList.add(list.get(i - 1));
            }
        }
        return rtnList;
    }

    /**
     * 还原指定活动节点流向
     * @author cg
     * @date 2019-09-02 20:20
     * @param activityImpl 活动节点
     * @param oriPvmTransitionList 原有节点流向集合
     */
    private void restoreTransition(ActivityImpl activityImpl,List<PvmTransition> oriPvmTransitionList) {
        // 清空现有流向
        List<PvmTransition> pvmTransitionList = activityImpl.getOutgoingTransitions();
        pvmTransitionList.clear();
        // 还原以前流向
        for (PvmTransition pvmTransition : oriPvmTransitionList) {
            pvmTransitionList.add(pvmTransition);
        }
    }

    /**
     * 清空指定活动节点流向
     * @author cg
     * @date 2019-09-02 19:49
     * @param activityImpl 活动节点
     * @return 节点流向集合
     */
    private List<PvmTransition> clearTransition(ActivityImpl activityImpl) {
        // 存储当前节点所有流向临时变量
        List<PvmTransition> oriPvmTransitionList = new ArrayList<PvmTransition>();
        // 获取当前节点所有流向，存储到临时变量，然后清空
        List<PvmTransition> pvmTransitionList = activityImpl
                .getOutgoingTransitions();
        for (PvmTransition pvmTransition : pvmTransitionList) {
            oriPvmTransitionList.add(pvmTransition);
        }
        pvmTransitionList.clear();
        return oriPvmTransitionList;
    }

}
